package io.seata.sample.service.impl;
import io.seata.sample.dao.OrderMapper;
import io.seata.sample.entity.Order;
import io.seata.sample.feign.AccountApi;
import io.seata.sample.feign.StockApi;
import io.seata.sample.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;

import java.math.BigDecimal;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author: linKe
 * @Date: 2022/1/25 10:35
 * @FileName: OrderServiceImpl
 * @version: 1.0
 * @Description: 描述
 */
@Service("orderServiceImpl")
public class OrderServiceImpl implements OrderService {

    private static final Logger LOGGER = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Resource
    private OrderMapper orderMapper;

    @Autowired
    private StockApi stockApi;
    @Autowired
    private AccountApi accountApi;

    /**
     * 创建订单
     *
     * @param order
     * @return 测试结果：
     * 1.添加本地事务：仅仅扣减库存
     * 2.不添加本地事务：创建订单，扣减库存
     */
    @Override
    @GlobalTransactional(name = "my_test_tx_group", rollbackFor = Exception.class)
    public void create(Order order) {
        LOGGER.info("------->交易开始");
        //本地方法
        orderMapper.create(order);
        LOGGER.info("[{},{},{}]",order.getProductId(), order.getCount(),accountApi.toString());

        //远程方法 扣减库存
        stockApi.decrease(order.getProductId(), order.getCount());

        //远程方法 扣减账户余额
        LOGGER.info("------->扣减账户开始order中");

        accountApi.decrease(order.getUserId(), order.getMoney());

        LOGGER.info("------->扣减账户结束order中");

        LOGGER.info("------->交易结束");
    }

    /**
     * 修改订单状态
     */
    @Override
    public void update(Long userId, BigDecimal money, Integer status) {
        LOGGER.info("修改订单状态，入参为：userId={},money={},status={}", userId, money, status);
        orderMapper.update(userId, money, status);
    }
}
